"""
配置变更审计模块 - 记录所有配置变更

这个模块实现了配置变更审计功能：
- 配置变更记录
- 变更历史追踪
- 回滚支持
- 变更审批流程
- 审计报告生成
"""

import asyncio
import logging
import time
import json
import hashlib
from dataclasses import dataclass, field
from datetime import datetime, timezone, timedelta
from enum import Enum
from typing import Any, Dict, List, Optional, Union, Callable, Tuple
from pathlib import Path
import difflib

logger = logging.getLogger(__name__)


class ChangeType(Enum):
    """变更类型"""
    CREATE = "create"          # 创建
    UPDATE = "update"          # 更新
    DELETE = "delete"          # 删除
    ROLLBACK = "rollback"      # 回滚
    IMPORT = "import"          # 导入
    EXPORT = "export"          # 导出


class ChangeStatus(Enum):
    """变更状态"""
    PENDING = "pending"        # 待审批
    APPROVED = "approved"      # 已审批
    REJECTED = "rejected"      # 已拒绝
    APPLIED = "applied"        # 已应用
    FAILED = "failed"          # 失败
    ROLLED_BACK = "rolled_back"  # 已回滚


class ApprovalLevel(Enum):
    """审批级别"""
    NONE = "none"              # 无需审批
    LOW = "low"                # 低级别
    MEDIUM = "medium"          # 中级别
    HIGH = "high"              # 高级别
    CRITICAL = "critical"      # 关键级别


@dataclass
class ConfigChange:
    """配置变更记录"""
    change_id: str
    change_type: ChangeType
    config_name: str
    config_type: str
    
    # 变更内容
    old_value: Optional[Any] = None
    new_value: Optional[Any] = None
    changes: List[Dict[str, Any]] = field(default_factory=list)
    
    # 元数据
    description: str = ""
    reason: str = ""
    tags: List[str] = field(default_factory=list)
    
    # 用户信息
    user_id: str = "system"
    user_name: str = "System"
    user_email: str = ""
    
    # 时间信息
    created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
    applied_at: Optional[datetime] = None
    
    # 审批信息
    approval_level: ApprovalLevel = ApprovalLevel.NONE
    approval_status: ChangeStatus = ChangeStatus.PENDING
    approver_id: Optional[str] = None
    approver_name: Optional[str] = None
    approved_at: Optional[datetime] = None
    approval_notes: str = ""
    
    # 影响评估
    impact_level: str = "low"  # low, medium, high, critical
    affected_services: List[str] = field(default_factory=list)
    risk_assessment: str = ""
    
    # 回滚信息
    can_rollback: bool = True
    rollback_data: Optional[Dict[str, Any]] = None
    rolled_back_at: Optional[datetime] = None
    rollback_reason: str = ""
    
    # 验证信息
    validation_passed: bool = True
    validation_errors: List[str] = field(default_factory=list)
    validation_warnings: List[str] = field(default_factory=list)


@dataclass
class AuditConfig:
    """审计配置"""
    # 存储配置
    storage_path: str = "audit_logs"
    max_entries: int = 100000
    retention_days: int = 365
    
    # 审批配置
    enable_approval: bool = True
    default_approval_level: ApprovalLevel = ApprovalLevel.MEDIUM
    auto_approve_levels: List[ApprovalLevel] = field(default_factory=lambda: [ApprovalLevel.NONE, ApprovalLevel.LOW])
    
    # 通知配置
    enable_notifications: bool = True
    notification_recipients: List[str] = field(default_factory=list)
    
    # 验证配置
    enable_validation: bool = True
    validation_rules: List[Dict[str, Any]] = field(default_factory=list)
    
    # 备份配置
    enable_backup: bool = True
    backup_interval: int = 3600  # 1小时
    backup_retention: int = 30   # 30天


class ConfigAuditManager:
    """配置审计管理器"""
    
    def __init__(self, config: Optional[AuditConfig] = None):
        self.config = config or AuditConfig()
        
        # 变更记录存储
        self.changes: Dict[str, ConfigChange] = {}
        self.change_history: List[str] = []  # 按时间排序的变更ID列表
        
        # 配置快照存储
        self.config_snapshots: Dict[str, Dict[str, Any]] = {}
        
        # 审批工作流
        self.approval_workflows: Dict[str, List[ApprovalLevel]] = {}
        
        # 回调函数
        self.change_callbacks: List[Callable] = []
        self.approval_callbacks: List[Callable] = []
        self.rollback_callbacks: List[Callable] = []
        
        # 锁
        self.lock = asyncio.Lock()
        
        # 存储目录
        self.storage_dir = Path(self.config.storage_path)
        self.storage_dir.mkdir(exist_ok=True)
        
        # 运行状态
        self.is_running = False
        self.cleanup_task: Optional[asyncio.Task] = None
        self.backup_task: Optional[asyncio.Task] = None
        
        self.logger = logging.getLogger(__name__)
        self.logger.info("配置审计管理器已初始化")
    
    async def start(self) -> None:
        """启动审计管理器"""
        if self.is_running:
            return
        
        self.is_running = True
        
        # 加载现有数据
        await self._load_existing_data()
        
        # 启动清理任务
        self.cleanup_task = asyncio.create_task(self._cleanup_worker())
        
        # 启动备份任务
        if self.config.enable_backup:
            self.backup_task = asyncio.create_task(self._backup_worker())
        
        self.logger.info("配置审计管理器已启动")
    
    async def stop(self) -> None:
        """停止审计管理器"""
        if not self.is_running:
            return
        
        self.is_running = False
        
        # 停止任务
        if self.cleanup_task:
            self.cleanup_task.cancel()
            try:
                await self.cleanup_task
            except asyncio.CancelledError:
                pass
        
        if self.backup_task:
            self.backup_task.cancel()
            try:
                await self.backup_task
            except asyncio.CancelledError:
                pass
        
        self.logger.info("配置审计管理器已停止")
    
    async def record_change(self, 
                           change_type: ChangeType,
                           config_name: str,
                           config_type: str,
                           old_value: Optional[Any] = None,
                           new_value: Optional[Any] = None,
                           description: str = "",
                           reason: str = "",
                           user_id: str = "system",
                           user_name: str = "System",
                           user_email: str = "",
                           tags: Optional[List[str]] = None) -> str:
        """记录配置变更"""
        async with self.lock:
            # 生成变更ID
            change_id = self._generate_change_id(change_type, config_name)
            
            # 计算变更差异
            changes = await self._calculate_changes(old_value, new_value)
            
            # 确定审批级别
            approval_level = await self._determine_approval_level(change_type, config_name, changes)
            
            # 评估影响
            impact_level, affected_services = await self._assess_impact(config_name, changes)
            
            # 验证变更
            validation_passed, validation_errors, validation_warnings = await self._validate_change(
                config_name, new_value, changes
            )
            
            # 创建变更记录
            change = ConfigChange(
                change_id=change_id,
                change_type=change_type,
                config_name=config_name,
                config_type=config_type,
                old_value=old_value,
                new_value=new_value,
                changes=changes,
                description=description,
                reason=reason,
                tags=tags or [],
                user_id=user_id,
                user_name=user_name,
                user_email=user_email,
                approval_level=approval_level,
                approval_status=ChangeStatus.PENDING if self.config.enable_approval else ChangeStatus.APPROVED,
                impact_level=impact_level,
                affected_services=affected_services,
                validation_passed=validation_passed,
                validation_errors=validation_errors,
                validation_warnings=validation_warnings,
                can_rollback=old_value is not None
            )
            
            # 保存变更记录
            self.changes[change_id] = change
            self.change_history.append(change_id)
            
            # 保存到文件
            await self._save_change_to_file(change)
            
            # 创建配置快照
            if new_value is not None:
                await self._create_config_snapshot(config_name, new_value, change_id)
            
            # 触发变更回调
            await self._trigger_change_callbacks(change)
            
            # 发送通知
            if self.config.enable_notifications:
                await self._send_notification(change)
            
            self.logger.info(f"配置变更已记录: {change_id}")
            return change_id
    
    async def approve_change(self, 
                            change_id: str,
                            approver_id: str,
                            approver_name: str,
                            approved: bool,
                            notes: str = "") -> bool:
        """审批配置变更"""
        async with self.lock:
            if change_id not in self.changes:
                self.logger.warning(f"变更记录不存在: {change_id}")
                return False
            
            change = self.changes[change_id]
            
            if change.approval_status != ChangeStatus.PENDING:
                self.logger.warning(f"变更状态不是待审批: {change_id}")
                return False
            
            # 更新审批信息
            change.approver_id = approver_id
            change.approver_name = approver_name
            change.approved_at = datetime.now(timezone.utc)
            change.approval_notes = notes
            
            if approved:
                change.approval_status = ChangeStatus.APPROVED
            else:
                change.approval_status = ChangeStatus.REJECTED
            
            # 保存更改
            await self._save_change_to_file(change)
            
            # 触发审批回调
            await self._trigger_approval_callbacks(change)
            
            # 发送通知
            if self.config.enable_notifications:
                await self._send_approval_notification(change)
            
            self.logger.info(f"配置变更审批完成: {change_id}, 结果: {'通过' if approved else '拒绝'}")
            return True
    
    async def apply_change(self, change_id: str) -> bool:
        """应用配置变更"""
        async with self.lock:
            if change_id not in self.changes:
                self.logger.warning(f"变更记录不存在: {change_id}")
                return False
            
            change = self.changes[change_id]
            
            if change.approval_status != ChangeStatus.APPROVED:
                self.logger.warning(f"变更未通过审批: {change_id}")
                return False
            
            try:
                # 这里应该调用实际的配置应用逻辑
                # 简化实现，只记录应用时间
                change.applied_at = datetime.now(timezone.utc)
                change.approval_status = ChangeStatus.APPLIED
                
                # 保存更改
                await self._save_change_to_file(change)
                
                self.logger.info(f"配置变更已应用: {change_id}")
                return True
                
            except Exception as e:
                change.approval_status = ChangeStatus.FAILED
                await self._save_change_to_file(change)
                self.logger.error(f"配置变更应用失败: {change_id}, 错误: {e}")
                return False
    
    async def rollback_change(self, 
                             change_id: str,
                             reason: str = "",
                             user_id: str = "system") -> bool:
        """回滚配置变更"""
        async with self.lock:
            if change_id not in self.changes:
                self.logger.warning(f"变更记录不存在: {change_id}")
                return False
            
            change = self.changes[change_id]
            
            if not change.can_rollback:
                self.logger.warning(f"变更不支持回滚: {change_id}")
                return False
            
            if change.approval_status != ChangeStatus.APPLIED:
                self.logger.warning(f"变更未应用，无法回滚: {change_id}")
                return False
            
            try:
                # 这里应该调用实际的回滚逻辑
                # 简化实现，只记录回滚信息
                change.rolled_back_at = datetime.now(timezone.utc)
                change.rollback_reason = reason
                change.approval_status = ChangeStatus.ROLLED_BACK
                
                # 保存更改
                await self._save_change_to_file(change)
                
                # 触发回滚回调
                await self._trigger_rollback_callbacks(change)
                
                self.logger.info(f"配置变更已回滚: {change_id}")
                return True
                
            except Exception as e:
                self.logger.error(f"配置变更回滚失败: {change_id}, 错误: {e}")
                return False
    
    async def get_change(self, change_id: str) -> Optional[ConfigChange]:
        """获取变更记录"""
        return self.changes.get(change_id)
    
    async def list_changes(self, 
                          config_name: Optional[str] = None,
                          change_type: Optional[ChangeType] = None,
                          status: Optional[ChangeStatus] = None,
                          user_id: Optional[str] = None,
                          limit: int = 100) -> List[ConfigChange]:
        """列出变更记录"""
        changes = []
        
        # 按时间倒序遍历
        for change_id in reversed(self.change_history):
            if len(changes) >= limit:
                break
            
            change = self.changes[change_id]
            
            # 应用过滤条件
            if config_name and change.config_name != config_name:
                continue
            if change_type and change.change_type != change_type:
                continue
            if status and change.approval_status != status:
                continue
            if user_id and change.user_id != user_id:
                continue
            
            changes.append(change)
        
        return changes
    
    async def get_config_history(self, config_name: str, limit: int = 50) -> List[ConfigChange]:
        """获取配置历史"""
        return await self.list_changes(config_name=config_name, limit=limit)
    
    async def get_pending_approvals(self) -> List[ConfigChange]:
        """获取待审批的变更"""
        return await self.list_changes(status=ChangeStatus.PENDING)
    
    async def generate_audit_report(self, 
                                   start_date: Optional[datetime] = None,
                                   end_date: Optional[datetime] = None,
                                   config_name: Optional[str] = None) -> Dict[str, Any]:
        """生成审计报告"""
        # 过滤变更记录
        filtered_changes = []
        for change_id in self.change_history:
            change = self.changes[change_id]
            
            if start_date and change.created_at < start_date:
                continue
            if end_date and change.created_at > end_date:
                continue
            if config_name and change.config_name != config_name:
                continue
            
            filtered_changes.append(change)
        
        # 统计信息
        stats = {
            "total_changes": len(filtered_changes),
            "by_type": {},
            "by_status": {},
            "by_user": {},
            "by_impact": {},
            "approval_rate": 0.0,
            "rollback_rate": 0.0
        }
        
        approved_count = 0
        rollback_count = 0
        
        for change in filtered_changes:
            # 按类型统计
            change_type = change.change_type.value
            stats["by_type"][change_type] = stats["by_type"].get(change_type, 0) + 1
            
            # 按状态统计
            status = change.approval_status.value
            stats["by_status"][status] = stats["by_status"].get(status, 0) + 1
            
            # 按用户统计
            user_id = change.user_id
            stats["by_user"][user_id] = stats["by_user"].get(user_id, 0) + 1
            
            # 按影响级别统计
            impact = change.impact_level
            stats["by_impact"][impact] = stats["by_impact"].get(impact, 0) + 1
            
            # 审批率统计
            if change.approval_status in [ChangeStatus.APPROVED, ChangeStatus.APPLIED]:
                approved_count += 1
            
            # 回滚率统计
            if change.approval_status == ChangeStatus.ROLLED_BACK:
                rollback_count += 1
        
        # 计算比率
        if len(filtered_changes) > 0:
            stats["approval_rate"] = approved_count / len(filtered_changes)
            stats["rollback_rate"] = rollback_count / len(filtered_changes)
        
        return {
            "report_generated_at": datetime.now(timezone.utc).isoformat(),
            "period": {
                "start_date": start_date.isoformat() if start_date else None,
                "end_date": end_date.isoformat() if end_date else None
            },
            "filter": {
                "config_name": config_name
            },
            "statistics": stats,
            "changes": [
                {
                    "change_id": change.change_id,
                    "change_type": change.change_type.value,
                    "config_name": change.config_name,
                    "description": change.description,
                    "user_id": change.user_id,
                    "created_at": change.created_at.isoformat(),
                    "approval_status": change.approval_status.value,
                    "impact_level": change.impact_level
                }
                for change in filtered_changes
            ]
        }
    
    async def _generate_change_id(self, change_type: ChangeType, config_name: str) -> str:
        """生成变更ID"""
        timestamp = int(time.time())
        hash_input = f"{change_type.value}:{config_name}:{timestamp}"
        hash_value = hashlib.md5(hash_input.encode()).hexdigest()[:8]
        return f"{change_type.value}_{config_name}_{timestamp}_{hash_value}"
    
    async def _calculate_changes(self, old_value: Any, new_value: Any) -> List[Dict[str, Any]]:
        """计算变更差异"""
        changes = []
        
        if old_value is None and new_value is not None:
            changes.append({
                "type": "added",
                "path": "",
                "old_value": None,
                "new_value": new_value
            })
        elif old_value is not None and new_value is None:
            changes.append({
                "type": "removed",
                "path": "",
                "old_value": old_value,
                "new_value": None
            })
        elif old_value != new_value:
            changes.append({
                "type": "modified",
                "path": "",
                "old_value": old_value,
                "new_value": new_value
            })
        
        return changes
    
    async def _determine_approval_level(self, 
                                       change_type: ChangeType,
                                       config_name: str,
                                       changes: List[Dict[str, Any]]) -> ApprovalLevel:
        """确定审批级别"""
        # 简化的审批级别确定逻辑
        if change_type == ChangeType.DELETE:
            return ApprovalLevel.HIGH
        elif len(changes) > 10:
            return ApprovalLevel.MEDIUM
        else:
            return self.config.default_approval_level
    
    async def _assess_impact(self, 
                            config_name: str,
                            changes: List[Dict[str, Any]]) -> Tuple[str, List[str]]:
        """评估影响"""
        # 简化的影响评估逻辑
        impact_level = "low"
        affected_services = []
        
        if len(changes) > 5:
            impact_level = "medium"
        elif len(changes) > 20:
            impact_level = "high"
        
        # 根据配置名称确定受影响的服务
        if "database" in config_name.lower():
            affected_services.append("database")
        if "api" in config_name.lower():
            affected_services.append("api_gateway")
        
        return impact_level, affected_services
    
    async def _validate_change(self, 
                              config_name: str,
                              new_value: Any,
                              changes: List[Dict[str, Any]]) -> Tuple[bool, List[str], List[str]]:
        """验证变更"""
        validation_passed = True
        validation_errors = []
        validation_warnings = []
        
        # 简化的验证逻辑
        if new_value is None and len(changes) > 0:
            validation_warnings.append("配置值被设置为空")
        
        # 这里可以添加更多的验证规则
        
        return validation_passed, validation_errors, validation_warnings
    
    async def _create_config_snapshot(self, 
                                     config_name: str,
                                     config_value: Any,
                                     change_id: str) -> None:
        """创建配置快照"""
        snapshot = {
            "config_name": config_name,
            "config_value": config_value,
            "change_id": change_id,
            "created_at": datetime.now(timezone.utc).isoformat()
        }
        
        self.config_snapshots[change_id] = snapshot
        
        # 保存到文件
        snapshot_file = self.storage_dir / f"snapshot_{change_id}.json"
        with open(snapshot_file, 'w') as f:
            json.dump(snapshot, f, indent=2, default=str)
    
    async def _save_change_to_file(self, change: ConfigChange) -> None:
        """保存变更记录到文件"""
        change_file = self.storage_dir / f"change_{change.change_id}.json"
        
        change_data = {
            "change_id": change.change_id,
            "change_type": change.change_type.value,
            "config_name": change.config_name,
            "config_type": change.config_type,
            "old_value": change.old_value,
            "new_value": change.new_value,
            "changes": change.changes,
            "description": change.description,
            "reason": change.reason,
            "tags": change.tags,
            "user_id": change.user_id,
            "user_name": change.user_name,
            "user_email": change.user_email,
            "created_at": change.created_at.isoformat(),
            "applied_at": change.applied_at.isoformat() if change.applied_at else None,
            "approval_level": change.approval_level.value,
            "approval_status": change.approval_status.value,
            "approver_id": change.approver_id,
            "approver_name": change.approver_name,
            "approved_at": change.approved_at.isoformat() if change.approved_at else None,
            "approval_notes": change.approval_notes,
            "impact_level": change.impact_level,
            "affected_services": change.affected_services,
            "risk_assessment": change.risk_assessment,
            "can_rollback": change.can_rollback,
            "rollback_data": change.rollback_data,
            "rolled_back_at": change.rolled_back_at.isoformat() if change.rolled_back_at else None,
            "rollback_reason": change.rollback_reason,
            "validation_passed": change.validation_passed,
            "validation_errors": change.validation_errors,
            "validation_warnings": change.validation_warnings
        }
        
        with open(change_file, 'w') as f:
            json.dump(change_data, f, indent=2, default=str)
    
    async def _load_existing_data(self) -> None:
        """加载现有数据"""
        try:
            # 加载变更记录
            for change_file in self.storage_dir.glob("change_*.json"):
                try:
                    with open(change_file, 'r') as f:
                        change_data = json.load(f)
                    
                    # 重建变更对象
                    change = ConfigChange(
                        change_id=change_data["change_id"],
                        change_type=ChangeType(change_data["change_type"]),
                        config_name=change_data["config_name"],
                        config_type=change_data["config_type"],
                        old_value=change_data.get("old_value"),
                        new_value=change_data.get("new_value"),
                        changes=change_data.get("changes", []),
                        description=change_data.get("description", ""),
                        reason=change_data.get("reason", ""),
                        tags=change_data.get("tags", []),
                        user_id=change_data.get("user_id", "system"),
                        user_name=change_data.get("user_name", "System"),
                        user_email=change_data.get("user_email", ""),
                        created_at=datetime.fromisoformat(change_data["created_at"]),
                        applied_at=datetime.fromisoformat(change_data["applied_at"]) if change_data.get("applied_at") else None,
                        approval_level=ApprovalLevel(change_data.get("approval_level", "none")),
                        approval_status=ChangeStatus(change_data.get("approval_status", "pending")),
                        approver_id=change_data.get("approver_id"),
                        approver_name=change_data.get("approver_name"),
                        approved_at=datetime.fromisoformat(change_data["approved_at"]) if change_data.get("approved_at") else None,
                        approval_notes=change_data.get("approval_notes", ""),
                        impact_level=change_data.get("impact_level", "low"),
                        affected_services=change_data.get("affected_services", []),
                        risk_assessment=change_data.get("risk_assessment", ""),
                        can_rollback=change_data.get("can_rollback", True),
                        rollback_data=change_data.get("rollback_data"),
                        rolled_back_at=datetime.fromisoformat(change_data["rolled_back_at"]) if change_data.get("rolled_back_at") else None,
                        rollback_reason=change_data.get("rollback_reason", ""),
                        validation_passed=change_data.get("validation_passed", True),
                        validation_errors=change_data.get("validation_errors", []),
                        validation_warnings=change_data.get("validation_warnings", [])
                    )
                    
                    self.changes[change.change_id] = change
                    self.change_history.append(change.change_id)
                
                except Exception as e:
                    self.logger.error(f"加载变更文件失败: {change_file}, 错误: {e}")
            
            # 按时间排序
            self.change_history.sort(key=lambda x: self.changes[x].created_at)
            
            self.logger.info(f"加载了 {len(self.changes)} 个变更记录")
        
        except Exception as e:
            self.logger.error(f"加载现有数据失败: {e}")
    
    async def _cleanup_worker(self) -> None:
        """清理工作线程"""
        while self.is_running:
            try:
                await self._cleanup_old_data()
                await asyncio.sleep(86400)  # 每天清理一次
            except asyncio.CancelledError:
                break
            except Exception as e:
                self.logger.error(f"清理任务异常: {e}")
                await asyncio.sleep(3600)
    
    async def _backup_worker(self) -> None:
        """备份工作线程"""
        while self.is_running:
            try:
                await self._backup_data()
                await asyncio.sleep(self.config.backup_interval)
            except asyncio.CancelledError:
                break
            except Exception as e:
                self.logger.error(f"备份任务异常: {e}")
                await asyncio.sleep(3600)
    
    async def _cleanup_old_data(self) -> None:
        """清理旧数据"""
        cutoff_date = datetime.now(timezone.utc) - timedelta(days=self.config.retention_days)
        
        # 清理过期的变更记录
        expired_changes = []
        for change_id, change in self.changes.items():
            if change.created_at < cutoff_date:
                expired_changes.append(change_id)
        
        for change_id in expired_changes:
            del self.changes[change_id]
            if change_id in self.change_history:
                self.change_history.remove(change_id)
            
            # 删除文件
            change_file = self.storage_dir / f"change_{change_id}.json"
            if change_file.exists():
                change_file.unlink()
        
        if expired_changes:
            self.logger.info(f"清理了 {len(expired_changes)} 个过期变更记录")
    
    async def _backup_data(self) -> None:
        """备份数据"""
        # 简化的备份实现
        backup_file = self.storage_dir / f"backup_{int(time.time())}.json"
        
        backup_data = {
            "backup_created_at": datetime.now(timezone.utc).isoformat(),
            "changes": {
                change_id: {
                    "change_id": change.change_id,
                    "change_type": change.change_type.value,
                    "config_name": change.config_name,
                    "created_at": change.created_at.isoformat(),
                    "approval_status": change.approval_status.value
                }
                for change_id, change in self.changes.items()
            }
        }
        
        with open(backup_file, 'w') as f:
            json.dump(backup_data, f, indent=2)
        
        self.logger.info(f"数据备份完成: {backup_file}")
    
    async def _trigger_change_callbacks(self, change: ConfigChange) -> None:
        """触发变更回调"""
        for callback in self.change_callbacks:
            try:
                if asyncio.iscoroutinefunction(callback):
                    await callback(change)
                else:
                    callback(change)
            except Exception as e:
                self.logger.error(f"变更回调执行失败: {e}")
    
    async def _trigger_approval_callbacks(self, change: ConfigChange) -> None:
        """触发审批回调"""
        for callback in self.approval_callbacks:
            try:
                if asyncio.iscoroutinefunction(callback):
                    await callback(change)
                else:
                    callback(change)
            except Exception as e:
                self.logger.error(f"审批回调执行失败: {e}")
    
    async def _trigger_rollback_callbacks(self, change: ConfigChange) -> None:
        """触发回滚回调"""
        for callback in self.rollback_callbacks:
            try:
                if asyncio.iscoroutinefunction(callback):
                    await callback(change)
                else:
                    callback(change)
            except Exception as e:
                self.logger.error(f"回滚回调执行失败: {e}")
    
    async def _send_notification(self, change: ConfigChange) -> None:
        """发送通知"""
        # 简化的通知实现
        self.logger.info(f"发送变更通知: {change.change_id}")
    
    async def _send_approval_notification(self, change: ConfigChange) -> None:
        """发送审批通知"""
        # 简化的通知实现
        self.logger.info(f"发送审批通知: {change.change_id}")
    
    def add_change_callback(self, callback: Callable) -> None:
        """添加变更回调"""
        self.change_callbacks.append(callback)
    
    def add_approval_callback(self, callback: Callable) -> None:
        """添加审批回调"""
        self.approval_callbacks.append(callback)
    
    def add_rollback_callback(self, callback: Callable) -> None:
        """添加回滚回调"""
        self.rollback_callbacks.append(callback)


# 全局配置审计管理器
_global_config_audit_manager: Optional[ConfigAuditManager] = None


def get_config_audit_manager() -> ConfigAuditManager:
    """获取全局配置审计管理器"""
    global _global_config_audit_manager
    if _global_config_audit_manager is None:
        _global_config_audit_manager = ConfigAuditManager()
    return _global_config_audit_manager
